package com.zpark.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zpark.util.ResultJsonUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 基于类级别的服务熔断
 */
@RestController
@RequestMapping("/hystrix")
@DefaultProperties(defaultFallback = "defaultFallback")
public class HystrixController {

    @GetMapping("/get")
    @HystrixCommand
    public ResultJsonUtil getAll(){
        int num = 1 / 0;
        return new ResultJsonUtil<>(2000, "SUCCESS", "请求成功");
    }

    @GetMapping("/date/{id}")
    @HystrixCommand
    public ResultJsonUtil getDate(@PathVariable Integer id){

        if (id == 1) {
            throw new RuntimeException("请求超时");
        }

        return new ResultJsonUtil<>(2000, "SUCCESS",
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }

    @GetMapping("/test")
    @HystrixCommand
    public ResultJsonUtil test(){

        // 模拟调用其他服务
        System.err.println("调用服务开始");

        try {
            // 让程序阻塞5秒，模拟请求超时，服务性能低下问题
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.err.println("调用服务结束");

        return new ResultJsonUtil<>(2000, "SUCCESS", new Date());
    }


    // 服务降级方法
    private ResultJsonUtil defaultFallback(){
        return new ResultJsonUtil<>(5000, "Error", "服务器繁忙，请稍后再试！");
    }
}
